package com.uqbar.arkanoid.components;

import java.awt.Color;
import java.awt.Graphics2D;

import com.uqbar.arkanoid.scenes.ArkanoidScene;
import com.uqbar.vainilla.DeltaState;
import com.uqbar.vainilla.GameComponent;
import com.uqbar.vainilla.appearances.Rectangle;
import com.uqbar.vainilla.colissions.CollisionDetector;

public class Bloque extends GameComponent<ArkanoidScene> {

	private int ancho = 80;
	private int alto = 20;
	private int x;
	private int y;
	private Pelota pelota;
	static double anguloMayor = Math.PI/3;
	static double anguloMenor = -Math.PI/3;
	
	
	
	public Pelota getPelota() {
		return pelota;
	}

	public void setPelota(Pelota pelota) {
		this.pelota = pelota;
	}

	public Bloque(Color color, int x, int y,Pelota ball){
		this.setAppearance(new Rectangle(color, ancho, alto));
		this.x=x;
		this.y=y;
		this.setPelota(ball);
	}
	
	public void onSceneActivated(){
		
		this.setX(x);
		this.setY(y);
		
		super.onSceneActivated();
	}
	
	public boolean colisionaConPelota(Pelota ball){
		return CollisionDetector.INSTANCE.collidesCircleAgainstRect(
				this.getPelota().getX(), this.getPelota().getY(), 
				this.getPelota().getAppearance().getWidth() / 2, this.getX(),
				this.getY(), this.getAppearance().getWidth(),
				this.getAppearance().getHeight());
	}
	
	public void definirAnguloSalida() {
		double puntoDeColision = this.obtenerPuntoDeColision();
		
		double anguloNuevo = ((anguloMayor - anguloMenor) / this
				.getAppearance().getWidth())
				* puntoDeColision
				+ anguloMenor;
		
		
		if(getPelota().getY() > this.getY()){
		this.getPelota().i = Math.sin(anguloNuevo) * -1;
		this.getPelota().j = Math.cos(anguloNuevo);
		}else{
			this.getPelota().i = Math.sin(anguloNuevo);
			this.getPelota().j = Math.cos(anguloNuevo) * -1;
		}

		
		
		if(this.getPelota().getY() > this.getPelota().getGame().getDisplayHeight())
			this.getPelota().setY(this.getPelota().getGame().getDisplayHeight());
		
	}

	public double obtenerPuntoDeColision() {
		if (this.getPelota().getX() > this.getX() && this.getPelota().getX() + this.getPelota().getAppearance().getWidth() < this.getX() + this.getAppearance().getWidth()) {
			double xCentroPelota = this.getPelota().getX() + this.getPelota().getAppearance().getWidth() / 2;
			return xCentroPelota - this.getX();
		} else if (this.getPelota().getX() < this.getX()) {
			return 0;
		} else {
			return this.getAppearance().getWidth();
		}
	}
	
	public void render(Graphics2D graphics) {
		super.render(graphics);
	}
	
	public void update(DeltaState deltaState) {

		if(this.colisionaConPelota(this.getPelota())){

			this.destroy();
			
			this.definirAnguloSalida();
			this.getScene().getMarcador().hit();
			
		}
		
		
		
		
		super.update(deltaState);
	}
	
	
}
